import express from 'express';
import db from './mongodb/db.js';
//config-lite 的说明是，在进程目录下寻找 config 文件夹, 然后再引用 default。
import config from 'config-lite';
import router from './routes/index.js';//所有路由
import cookieParser from 'cookie-parser';//cookie parse
import session from 'express-session';//session
import connectMongo from 'connect-mongo';//
import winston from 'winston';// winston 和 express-winston 有什么区别啊！！
import expressWinston from 'express-winston';// winston 记录日记
import path from 'path';
import history from 'connect-history-api-fallback';//h5 跳转？？
import Statistic from './middlewares/statistic'

//初始化
const app = express();

//跨域
app.all('*', (req, res, next) => {
	res.header("Access-Control-Allow-Origin",  req.headers.origin || '*');
	res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  	res.header("Access-Control-Allow-Credentials", true); //可以带cookies
	res.header("X-Powered-By", '3.2.1');
	if (req.method == 'OPTIONS') {
	  	res.send(200);
	} else {
	    next();
	}
});


//Record？？？？？？
app.use(Statistic.apiRecord);

//session 卧槽！！！什么鬼啊
const MongoStore = connectMongo(session);
app.use(cookieParser());
app.use(session({
	  	name: config.session.name,
		secret: config.session.secret,
		resave: true,
		saveUninitialized: false,
		cookie: config.session.cookie,
		store: new MongoStore({
	  	    url: config.url
	    })
}));

//成功日记
app.use(expressWinston.logger({
    transports: [
        new (winston.transports.Console)({
          json: true,
          colorize: true
        }),
        new winston.transports.File({
          filename: 'logs/success.log'
        })
    ]
}));
router(app);

//错误日记
app.use(expressWinston.errorLogger({
    transports: [
        new winston.transports.Console({
          json: true,
          colorize: true
        }),
        new winston.transports.File({
          filename: 'logs/error.log'
        })
    ]
}));

app.use(history());
app.use(express.static('./public'));
app.listen(config.port);